<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.freight') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('freight-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-input v-model="query.name" type="text" :placeholder="$t('table.ForeignLanguageName')" />
        </el-col>
        <el-col :span="4">
          <el-select v-model.number="query.status" :placeholder="$t('table.selectThe')+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="650px" style="margin-top: 20px;">
        <el-table-column :label="$t('table.templateId')" prop="id" width="100" />
        <el-table-column :label="$t('table.ForeignLanguageName')" prop="name" />
        <el-table-column :label="$t('table.ChName')" prop="sub_name" />
        <el-table-column :label="$t('table.RegionandPrice')" prop="pricedata" width="400">
          <template slot-scope="{row}">
            <div v-html="pricedataHtml(row.pricedata)" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.state')" prop="status">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|formatEmployment }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" :label="$t('table.sort')" width="250">
          <template slot-scope="{row}">
            <template v-if="row.isedit">
              <el-input v-model="row.sort" class="edit-input" size="small" style="width: 50%;" />
              <el-button
                style="margin-left: 10px;"
                class="cancel-btn"
                size="small"
                icon="el-icon-refresh"
                type="warning"
                @click="confirmEdit(row)"
              >
                {{ $t('button.confirm') }}
              </el-button>
            </template>
            <span v-else>{{ row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="created_at">
          <template slot-scope="{row}">
            {{ row.createtime|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="380" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('freight-edit')" @click="addOrEidt('edit',row)">{{ $t('button.edit') }}</el-button>
            <el-button v-if="row.isedit" type="warning" size="mini" @click="cancelEdit(row)">
              {{ $t('button.cancel') }}
            </el-button>
            <el-button v-else type="warning" size="mini" :disabled="!checkPermission('freight-set')" @click="paixu(row)">
              {{ $t('table.sort') }}
            </el-button>
            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('freight-del')" @click="delData(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" width="70%" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="220px">
        <el-form-item :label="$t('table.freight_text')">
          <el-radio v-model.number="formData.pstype" :label="0">{{ $t('table.delivery') }}</el-radio>
          <!-- <el-radio v-model.number="formData.pstype" :label="1">到店自提</el-radio>
          <el-radio v-model.number="formData.pstype" :label="2">同城配送</el-radio> -->
        </el-form-item>
        <el-form-item :label="$t('table.ForeignLanguageName')" prop="name">
          <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+' '+$t('table.ForeignLanguageName')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.ChName')">
          <el-input v-model="formData.sub_name" :placeholder="$t('table.enterThe')+' '+$t('table.ChName')" style="width:50%" />
        </el-form-item>
        <el-form-item :label="$t('table.Pricingmethod')">
          <el-radio v-model.number="formData.type" :label="1">{{ $t('table.Byweight') }}</el-radio>
          <el-radio v-model.number="formData.type" :label="2">{{ $t('table.Bypiece') }}</el-radio>
        </el-form-item>
        <el-form-item :label="$t('table.RegionandPrice')">
          <table class="ljm-table" cellspacing="0" cellpadding="0">
            <thead>
              <tr>
                <th>{{ $t('table.Region') }}</th>
                <th>{{ $t('table.DeliveryOrNot') }}</th>
                <template v-if="formData.type===1">
                  <th>{{ $t('table.InitialWeight') }}(g)</th>
                  <th>{{ $t('table.Firstweightcost') }}(R$)</th>
                  <th>{{ $t('table.Excessweight') }}(g)</th>
                  <th>{{ $t('table.Excessweightcharge') }}(R$)</th>
                </template>
                <template v-else>
                  <th>{{ $t('table.Initialquantity') }}</th>
                  <th>{{ $t('table.Initialcost') }}(R$)</th>
                  <th>{{ $t('table.Excessquantity') }}</th>
                  <th>{{ $t('table.Excesscost') }}(R$)</th>
                </template>
                <th>{{ $t('table.actions') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in pricedataList" :key="index">
                <td>
                  <label style="margin-right: 10px;">{{ item.region }}</label>
                  <el-button v-if="index!==0" size="mini" @click="openRegion(index)">{{ $t('button.edit') }}</el-button>
                </td>
                <td>
                  <el-switch v-model="item.ispeisong" active-value="1" inactive-value="0" />
                </td>
                <td><input v-model="item.fristweight" class="layui-input" type="text" style="width:60px;"></td>
                <td><input v-model="item.fristprice" class="layui-input" type="text" style="width:60px;"></td>
                <td><input v-model="item.secondweight" class="layui-input" type="text" style="width:60px;"></td>
                <td><input v-model="item.secondprice" class="layui-input" type="text" style="width:60px;"></td>
                <td>
                  <el-button v-if="index===0" type="primary" size="mini" @click="addPricedata">{{ $t('button.add') }}</el-button>
                  <el-button v-else type="primary" size="mini" @click="removePricedata(index)">{{ $t('button.delete') }}</el-button>
                </td>
              </tr>
            </tbody>
          </table>
        </el-form-item>
        <el-form-item :label="$t('table.Freeshippingamount')">
          <el-switch v-model.number="formData.freeset" :active-value="1" :inactive-value="0" />
          <template v-if="formData.freeset===1">
            <label style="margin-left: 20px;">{{ $t('table.full') }}</label>
            <el-input v-model="formData.free_price" style="width:8%;margin-left: 10px;" />
            <label style="margin-left: 10px;">{{ $t('table.FreeShipping') }}</label>
          </template>
        </el-form-item>
        <el-form-item :label="$t('table.state')" prop="status">
          <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
            <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 选择区域 -->
    <el-dialog :title="$t('table.Selectregion')" :visible="DialogRegion" @close="btnCanle1">
      <div>
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="(item,index) in provinces" :key="index" :label="item.provinceName" style="margin: 10px 10px;" />
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle1">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="RegionOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Cookies from 'js-cookie'
import { getFreightList, addFreight, delFreight, sortFreight } from '@/api/user'
import user from '@/store/modules/user'
import employees from '@/api/employees'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: this.$t('table.normal')
      },
      {
        id: 2,
        value: this.$t('table.deactivate')
      }],
      query: {
        id: undefined,
        name: '',
        status: undefined,
        aid: 1,
        page: 1,
        limit: 10
      },
      count: 0,
      dialogTitle: this.$t('button.add'),
      formData: {
        aid: 1,
        id: undefined,
        pstype: 0,
        name: '',
        sub_name: '',
        type: 1,
        pricedata: '',
        status: undefined,
        bid: undefined,
        freeset: 0,
        free_price: undefined,
        formdata: '[{"key":"input","val1":"备注","val2":"选填，请输入备注信息","val3":0}]',
        pstimedata: '[{"day":"1","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"1","hour":"18","minute":"0","hour2":"18","minute2":"30"},{"day":"2","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"2","hour":"18","minute":"0","hour2":"18","minute2":"30"}]'
      },
      rules: {
        name: [{ required: true, message: this.$t('table.name') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false,
      DialogRegion: false,
      pricedataList: [
        { fristprice: '10', fristweight: '1000', ispeisong: '1', region: '全国(默认运费)', secondprice: '0', secondweight: '1000' }
      ],
      curRegionIndex: undefined,
      checkList: [],
      provinces: employees.provinces
    }
  },
  created() {
    // 获取userid
    this.getList()
    this.formData.bid = parseFloat(user.state.userInfo.bid)
  },
  methods: {
    // 确定区域选择
    RegionOk() {
      console.log(this.checkList)
      this.pricedataList[this.curRegionIndex].region = this.checkList.join(';')
      this.btnCanle1()
    },
    // 打开区域选择
    openRegion(index) {
      this.curRegionIndex = index// 设置当前要设置pricedataList索引
      if (this.pricedataList[this.curRegionIndex].region === '') {
        this.checkList = []
      } else {
        this.checkList = this.pricedataList[this.curRegionIndex].region.split(';')
      }

      this.DialogRegion = true
    },
    // 移除当前的区域价格
    removePricedata(index) {
      this.pricedataList.splice(index, 1)
    },
    // 新增一条区域价格
    addPricedata() {
      const one = { fristprice: '', fristweight: '', ispeisong: '1', region: '', secondprice: '', secondweight: '' }
      this.pricedataList.push(one)
    },
    // 获取列表
    async getList() {
      this.downloadLoading = true
      const { count, list } = await getFreightList(this.query)
      this.count = count
      // 给数组对象使用map循环添加新属性
      const lists = list.map((item, index) => {
        return Object.assign(item, { isedit: false })
      })
      this.list = lists
      this.downloadLoading = false
    },
    // 点击展开新增修改
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('button.add')
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('button.edit')
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.status = row.status
        this.formData.sub_name = row.sub_name
        this.formData.pstype = row.pstype
        this.formData.type = row.type
        this.formData.free_price = row.free_price
        this.formData.freeset = row.freeset
        if (row.pricedata !== '') {
          this.pricedataList = JSON.parse(row.pricedata)
        }
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        // 添加区域价格数据
        this.formData.pricedata = JSON.stringify(this.pricedataList)
        this.formData.free_price = parseFloat(this.formData.free_price)
        // 调用新增接口
        await addFreight(this.formData)
        // 更新数据
        this.getList()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除
    async delData(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delFreight(data)
        this.getList()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        aid: 1,
        id: undefined,
        pstype: 0,
        name: '',
        sub_name: '',
        type: 1,
        pricedata: '',
        status: undefined,
        bid: undefined,
        freeset: 0,
        formdata: '[{"key":"input","val1":"备注","val2":"选填，请输入备注信息","val3":0}]',
        pstimedata: '[{"day":"1","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"1","hour":"18","minute":"0","hour2":"18","minute2":"30"},{"day":"2","hour":"12","minute":"0","hour2":"12","minute2":"30"},{"day":"2","hour":"18","minute":"0","hour2":"18","minute2":"30"}]'
      }
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 取消区域选择
    btnCanle1() {
      this.checkList = []
      this.DialogRegion = false
    },
    // 点击排序
    paixu(row) {
      row.isedit = true
    },
    // 取消排序
    cancelEdit(row) {
      row.isedit = false
    },
    // 确认排序
    async confirmEdit(row) {
      const data = {
        id: row.id,
        sort: parseInt(row.sort)
      }
      row.isedit = false
      try {
        await sortFreight(data)
        this.$message.success(this.$t('prompt.paixuSuccess'))
        this.getList()
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getList()
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getList()
    },
    pricedataHtml(cellValue) {
      if (cellValue !== undefined && cellValue !== '') {
        const data = JSON.parse(cellValue)
        let html = ''
        data.forEach(element => {
          if (Cookies.get('language') === 'zh') {
            html += '<b>' + element.region + ':</b><br> ' + element.fristweight + '克以下 R$' + element.fristprice + '，每超出' + element.secondweight + '克加 R$' + element.secondprice + '<br>'
          } else {
            html += '<b>' + element.region + ':</b><br> Below ' + element.fristweight + ' gram, R$' + element.fristprice + '; for each additional' + element.secondweight + ' grams, add R$' + element.secondprice + '<br>'
          }
        })
        return html
      }
    }
  }
})
</script>
<style lang="scss">
.table-img{
  width: 90px;
}
.ljm-table{
  thead{
    tr{
      background-color: #f2f2f2;
      th{
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        text-align: left;
      }
    }
  }
  tbody{
    tr{
      margin-top: -1px;
      td{
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        .layui-input{
          display: inline;
          height: 30px;
          padding-left: 10px;
          line-height: 1.3;
          border-width: 1px;
          border-style: solid;
          background-color: #fff;
          border-radius: 2px;
          border-color: #e6e6e6;
        }
        div{
          margin: 5px 0px;
          .layui-btn-sm{
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
            font-size: 12px;
            margin-left: 5px;
          }
          .layui-btn-primary{
            border: 1px solid #C9C9C9;
            background-color: #fff;
            color: #555;
          }
          .layui-btn {
              display: inline-block;
              white-space: nowrap;
              text-align: center;
              border-radius: 2px;
              cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
